﻿using System.Collections.Generic;
using System.Linq;
using ReactiveGraph.Core;
using ReactiveGraph.Core.Extensions;
using ReactiveGraph.Extensions.Rules.Core;

namespace ReactiveGraph.Extensions.Rules
{
    public class NodeRules : IExtension
    {
        internal const string RulesPropertyName = "ReactiveGraph.Extensions.Rules";

        public void ConfigureContainer(IReactiveNodeContainer reactiveNodeContainer)
        {
            reactiveNodeContainer.Get<NodeDefaults>()
                .RegisterProperty<IReactiveNode, Property<List<IDeclared<NodeEvent>>>, List<IDeclared<NodeEvent>>>(
                RulesPropertyName,() => new List<IDeclared<NodeEvent>>()
                );
            reactiveNodeContainer.Get<NodeDefaults>()
                .RegisterBehaviour<IReactiveNode>(node => node.Events.Do(e => RunThroughRules(e, node.Rules())).ToUnit());
        }

        private static void RunThroughRules(NodeEvent nodeEvent, IEnumerable<IDeclared<NodeEvent>> rules)
        {
            rules.Run(declared => declared.Execute(nodeEvent));
        }
    }
}
